<?php
session_start();
include_once("../../untils/conn.php");
mysqli_query($con, "set names utf8");
$name = $_POST['username'];
$pwd = $_POST['password'];
$token = $_POST['token'];

// 验证账号、密码和令牌是否为空
if (empty($name) || empty($pwd) || empty($token)) {
    echo "<script>alert('账号、密码和令牌不能为空');history.go(-1);</script>";
    exit;
}

// 从数据库获取盐值和安全令牌
$sql = "SELECT salt, token FROM admin WHERE user='$name';";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$dbToken = $row['token'];

// 在查询中使用明文密码进行验证
$sql = "SELECT user, password FROM admin WHERE user='$name' AND password='$pwd';";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
$_SESSION["username"] = $name;

if ($row) {
    // 验证通过
    $hashedToken = md5($token . $salt); // 使用盐值对用户输入的令牌进行加密处理
    if ($hashedToken === $dbToken) {
        echo "<script>alert('登录成功');location.href='../index.php';</script>";
    } else {
        echo "<script>alert('安全令牌错误');history.go(-1);</script>";
    }
} else {
    // 验证失败
    echo "<script>alert('用户名或密码错误，请重新输入');history.go(-1);</script>";
}
?>
